package h3

import (
	"bytes"
	"fmt"
	"github.com/lucas-clemente/quic-go"
	"github.com/lucas-clemente/quic-go/quicvarint"
	"io"
)

//SettingFrame
//  SETTINGS Frame {
//		Type (i) = 0x4,
//		Length (i),
//		Setting (..) ...,
//	}
//
//	Setting {
//		Identifier (i),
//		Value (i),
//	}
type SettingFrame struct {
	Payload map[uint64]uint64
}

func (f *SettingFrame) ToBytes() []byte {
	buf := bytes.Buffer{}
	// Type
	quicvarint.Write(&buf, SettingFrameType)
	// Length
	length := uint64(0)
	for key, val := range f.Payload {
		length += uint64(quicvarint.Len(key) + quicvarint.Len(val))
	}
	quicvarint.Write(&buf, length)
	for key, val := range f.Payload {
		quicvarint.Write(&buf, key)
		quicvarint.Write(&buf, val)
	}
	return buf.Bytes()
}

func ParseSettingFrame(uniStream quic.ReceiveStream) *SettingFrame {
	reader := quicvarint.NewReader(uniStream)
	frameType, _ := quicvarint.Read(reader)
	if SettingFrameType == frameType {
		// setting 帧
		length, _ := quicvarint.Read(reader)
		payloadBuf := make([]byte, length)
		payload := make(map[uint64]uint64)
		_, _ = io.ReadFull(uniStream, payloadBuf)
		payloadReader := bytes.NewReader(payloadBuf)
		for payloadReader.Len() > 0 {
			key, _ := quicvarint.Read(payloadReader)
			val, _ := quicvarint.Read(payloadReader)
			payload[key] = val
		}
		return &SettingFrame{Payload: payload}
	} else {
		fmt.Printf("%d not support\n", frameType)
		SkipUnknownFrame(uniStream)
		return nil
	}
}
